package com.dp.mallchat.common.common.inteceptor;

import com.dp.mallchat.common.common.domain.dto.RequestInfo;
import com.dp.mallchat.common.common.domain.enums.HttpErrorEnum;
import com.dp.mallchat.common.common.utils.RequestHolder;
import com.dp.mallchat.common.user.dao.BlackDao;
import com.dp.mallchat.common.user.domain.user.enums.BlackTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @Author: dupeng
 * @CreateTime: 2024-06-13  17:16
 * @Description: 黑名单拦截器
 */
@Component
@Slf4j
@Order(3)
public class BlackInterceptor implements HandlerInterceptor {

    @Autowired
    private BlackDao blackDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1、获取用户信息
        RequestInfo threadLocal = RequestHolder.getThreadLocal();

        //2、判断uid是否被拉黑
        Map<Integer, Set<String>> blackList = blackDao.blackList();

        boolean isPass = isPass(blackList.get(BlackTypeEnum.UID.getType()), threadLocal.getUid());
        if (!isPass) {
            HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
            return false;
        }

        //3、判断ip是否被拉黑
        isPass = isPass(blackList.get(BlackTypeEnum.IP.getType()), threadLocal.getIp());
        if (!isPass) {
            HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
            return false;
        }
        return true;
    }

    private boolean isPass(Set<String> Object, Object target) {

        if (CollectionUtils.isEmpty(Object) || Objects.isNull(target)) {
            return true;
        }
        return !Object.contains(target.toString());
    }
}
